﻿using System;
using System.Data.Common;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Solution.Comm.DomainInterfaces;

namespace Solution.EntityFrameworkCore
{
    public class UnitOfWork<TDbContext> : IUnitOfWork where TDbContext : DbContext
    {

        private readonly TDbContext _dbContext;

        public UnitOfWork(TDbContext context)
        {
            _dbContext = context ?? throw new ArgumentNullException(nameof(context));
        }
        //protected readonly SolutionDbContext _dbContext;

        //public UnitOfWork(SolutionDbContext solutionDb)
        //{
        //    _dbContext = solutionDb;
        //}

        //protected DbContext _Context => _dbContext;

        public DbTransaction BeginTransaction()
        {
            _dbContext.Database.BeginTransaction();

            return _dbContext.Database.CurrentTransaction.GetDbTransaction();
        }

        public void Commit()
        {
            _dbContext.SaveChanges();
        }

        public Task CommitAsync()
        {
            return _dbContext.SaveChangesAsync();
        }

        public void CommitTransaction()
        {
            _dbContext.SaveChanges();
            _dbContext.Database.CommitTransaction();
        }

        public void Dispose()
        {
            if (_dbContext != null) {
                _dbContext.Dispose();
            }

            GC.SuppressFinalize(this);
        }

        public void RollbackTransaction()
        {
            _dbContext.Database.RollbackTransaction();
        }
       
    }
}